package com.duartepeixinho.P3D.Materials 
{
	import com.duartepeixinho.P3D.Core.Geom.Face3;
	import com.duartepeixinho.P3D.Lights.PointLight;
	import flash.display.Graphics;
	import flash.geom.Point;
	/**
	 * P3D
	 * @version 0.1
	 * @author Duarte Peixinho
	 */
	public class FlatShadedMaterial extends AbstractLighMaterial implements IMaterials
	{		
		
		public function FlatShadedMaterial(light:PointLight, lightColor:uint = 0xffffff, doubleSided:Boolean = false) 
		{
			_light = light;
			this.color = lightColor;
			this.doubleSided = doubleSided;			
		}
		
		/**
		 * Get Light Factor
		 * @param	tri		Face3
		 * @return			Number
		 */
		private function getLightFactor(tri:Face3):Number
		{
			var dotProd:Number = 	tri.normal.x * _light.x +
									tri.normal.y * _light.y +
									tri.normal.z * _light.z;
									
			var normMag:Number = tri.normal.length();
			var lightMag:Number = _light.position.length();
			return (Math.acos(dotProd / (normMag * lightMag)) / Math.PI) * _light.brightness;
		}
		/**
		 * Get Color
		 * @param	tri		Face3
		 * @return			Number
		 */
		private function getAdjustedColor(tri:Face3):uint
		{
			var red:Number = color >> 16;
			var green:Number = color >> 8 & 0xff;
			var blue:Number = color & 0xff;
			var lightFactor:Number = getLightFactor(tri);
			red *= lightFactor;
			green *= lightFactor;
			blue *= lightFactor;
			return red << 16 | green << 8 | blue;
			}

		override public function drawTriangle(tri:Face3,A:Point,B:Point,C:Point,graphics:Graphics):void 
		{			
			graphics.lineStyle();
			graphics.beginFill(getAdjustedColor(tri));
			graphics.moveTo(A.x, A.y);
			graphics.lineTo(B.x, B.y);
			graphics.lineTo(C.x, C.y);
			graphics.lineTo(A.x, A.y);
			graphics.endFill();
		}
		
	}

}